<?php
/**
 * Created by PhpStorm.
 * User: jsq
 * Date: 2017/12/1 0001
 * Time: 16:46
 */

namespace app\admin\logic;

use app\admin\model\Area as Area_model;
use think\Cache;

class Area
{
    private $area_model = '';

    public function __construct(){
        $this->area_model = new Area_model();
    }

    /**
     * 获取所有的地区（供获取器使用）
     * @return array|false|mixed|\PDOStatement|string|\think\Collection
     */
    public static function areasToText(){
        $states = self::getAllAreas();
        $states = collect($states)->column('name','id');
        return $states;
    }

    /**
     * 获得所有的地区（从缓存中）
     * @return false|mixed|\PDOStatement|string|\think\Collection   返回数组
     */
    public function getAllAreas(){
        if (!empty(Cache::get('allAreas'))){
            return Cache::get('allAreas');
        }else{
            $states = Area_model::all();
            Cache::set('allAreas',$states);
            return $states;
        }
    }

    /**
     * 获取启用的地区
     * @return array|false|mixed|\PDOStatement|string|\think\Collection
     */
    public function getEnabledAreas(){
        $states = $this->getAllAreas();
        $states = collect($states)->where('status',1)->all();
        $states = collection($states)->toArray();
        $states = array_merge($states);
        return $states;
    }

    public function addArea($data){
        if(empty($data)){
            return ['result'=>2,'msg'=>'数据丢失'];
        }
        $data['status'] = 1;//自动启用
        $result = $this->area_model->allowField(true)->validate(true)->save($data);
        if($result == false){
            return ['result'=>2,'msg'=>$this->area_model->getError()];
        }else{
            Cache::rm('allAreas');
            return ['result'=>1,'msg'=>'新增成功'];
        }
    }

    public function editArea($data){
        if(empty($data)){
            return ['result'=>2,'msg'=>'数据丢失'];
        }
        if(empty($data['id'])){
            return ['result'=>2,'msg'=>'ID丢失'];
        }
        $result = $this->area_model->allowField(true)->validate('Area.edit')->isUpdate(true)->save($data);
        if($result == false){
            return ['result'=>2,'msg'=>$this->area_model->getError()?:'没有需要修改的数据'];
        }else{
            Cache::rm('allAreas');
            return ['result'=>1,'msg'=>'修改成功'];
        }
    }

    public function delArea($id)
    {
        if (empty($id)) {
            return ['result' => false, 'msg' => '请选择要操作的数据'];
        }
        if (Area_model::get($id)) {
            if (Area_model::destroy($id)) {
                Cache::rm('allAreas');
                return ['result' => true, 'msg' => '删除成功'];
            } else {
                return ['result' => false, 'msg' => '删除失败'];
            }
        } else {
            return ['result' => false, 'msg' => '要删除的数据不存在'];
        }
    }




}